const Task = require('../models/task')
const User = require('../models/user')
const Category = require('../models/category')
const Taskaudit = require('../models/taskaudit')
const response = require('../utils/response')
const loop = require('../utils/loop')
const fs = require('fs')
let path = require('path')
const task = require('../models/task')

//工具
const {
    countProcess,
    deletaTask,
    huanTime
} = require('../utils/tool')

// 获取任务列表
exports.getTasks = async (req, res, next) => {
    try {
        var limitNumber = Number(req.query.limitNumber) || Number(5)
        var skipNumber = Number(req.query.skipNumber) || Number(0)
        const userId = req.params.userId
        const workerTask = await Task.find({
                worker: userId,
            })
            .populate('worker', ['name'])
            .populate('creator', ['name'])
            .populate('parentId', ['taskname'])
            .sort({
                _id: -1
            })
            .skip(skipNumber) //跳过前sortNumber文档
            .limit(limitNumber) //查询后面的limitNumber个文档
            .lean()

        //查询上传文件人
        for (let i in workerTask) {
            for (let a in workerTask[i].fileAddress) {
                let arr = workerTask[i].fileAddress[a]
                if (arr.userId) {
                    let user = await User.findById(arr.userId)
                    arr.user = user
                }
            }
        }

        const workerTaskCount = await Task.find({
            worker: userId
        }).countDocuments()
        await loop.deanTask(workerTask)

        const creatorTask = await Task.find({
                creator: userId
            })
            .populate('worker', ['name'])
            .populate('creator', ['name'])
            .populate('parentId', ['taskname'])
            .skip(skipNumber) //跳过前sortNumber文档
            .limit(limitNumber) //查询后面的limitNumber个文档
            .sort({
                _id: -1
            })
            .lean()

        //查询上传文件人
        for (let i in creatorTask) {
            for (let a in creatorTask[i].fileAddress) {
                let arr = creatorTask[i].fileAddress[a]
                if (arr.userId) {
                    let user = await User.findById(arr.userId)
                    arr.user = user
                }
            }
        }

        const creatorTaskCount = await Task.find({
            creator: userId
        }).countDocuments()
        await loop.deanTask(creatorTask)
        response(res, 200, '成功', {
            workerTask, //负责的任务
            creatorTask, //创建的任务
            workerTaskCount, //负责的数量
            creatorTaskCount //创建的任务数量
        })
    } catch (err) {
        next(err)
    }
}

// 获取任务
exports.getTask = async (req, res, next) => {
    try {
        var task = await Task.find({
                "_id": req.params.taskId
            })
            .populate('worker', ['name'])
            .populate('creator', ['name'])
            .populate('parentId', ['taskname'])
            .lean()

        //查询上传文件人
        // for (let i in task) {
        //     for (let a in task[i].fileAddress) {
        //         let arr = task[i].fileAddress[a]
        //         if (arr.userId) {
        //             let user = await User.findById(arr.userId)
        //             arr.user = user
        //         }
        //     }
        // }

        if (!task) {
            response(res, 404, '找不到该任务', task)
        }
        await loop.deanTask(task)
        response(res, 200, '成功', task)
    } catch (err) {
        next(err)
    }
}

// 分解任务
exports.submitTask = async (req, res, next) => {
    try {
        // const files = req.files
        // req.body.fileAddress = files
        var task = new Task(req.body)
        task.status = 0
        task.process = 0

        let taskOne = await Task.findById(req.body.parentId)
        task.grade = (taskOne.grade) + 1

        // 更正时间
        task.endtime = huanTime(task.endtime)
        task.createdAt = huanTime(Date.now())
        task.updatedAt = huanTime(Date.now())
        
        await task.save()

        // req.oldData = {}
        req.newData = task
        req.operate = 2
        next()
        // response(res, 200, '成功', {
        //     task
        // })
    } catch (err) {
        next(err)
    }
}

// 提交任务
exports.referTask = async (req, res, next) => {
    try {
        // const files = req.files
        // req.body.files = files
        const task = req.task

        // 校验任务是否是底层任务
        if (req.body.process) {
            let taskOne = await Task.find({
                parentId: task._id
            })
            if (taskOne.length > 0) return response(res, 401, '该任务不是底层任务，禁止修改进度~~', null)
            // res.send(taskOne)
            // return
        }

        // 修改进度
        task.process = req.body.process || task.process
        // 查找用户
        let user = await User.findById(req.body.userId)
        // 存入文件
        task.fileAddress.push({
            describe: req.body.describe, //描述
            // userId:req.body.userId, 
            name: user.name,
            files: req.body.files, //文件
            process: req.body.process, //进度

        })
        // await task.save()
        // 更正时间
        task.updatedAt = huanTime(Date.now())
        const model = await Task.findByIdAndUpdate(req.params.taskId, task)

        //计算进度
        await countProcess(task.parentId)

        // 进度100 改变状态
        if (task.process === 100) {

            //任务状态：已完成
            task.status = 1
            task.updatedAt = huanTime(Date.now())
            await Task.findByIdAndUpdate(req.params.taskId, task)
        }
        //提交到审核表
        const auditFrom = {
            taskId: task._id,
            fileId: task.fileAddress[task.fileAddress.length - 1]._id,
            taskname: task.taskname,
            reviewer: task.creator,
            grade: task.grade,
            process: task.process,
            createdAt: huanTime(Date.now()),
            updatedAt: huanTime(Date.now()),
        }
        await Taskaudit.create(auditFrom)

        // req.oldData = model //返回的旧数据
        // req.newData = task //新数据
        // req.operate = 0
        // next()

        response(res, 200, '成功', task)
    } catch (err) {
        next(err)
    }
}

// 更新任务
exports.updataTask = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const task = req.task
        const bodyTask = req.body
        // res.send(bodyTask)
        // return

        task.taskname = bodyTask.taskname || task.taskname
        task.worker = bodyTask.worker || task.worker
        task.describe = bodyTask.describe || task.describe
        task.endtime = huanTime(bodyTask.endtime) || task.endtime
        task.updatedAt = huanTime(Date.now())

        let oldData = await Task.findByIdAndUpdate(taskId, task)

        req.oldData = oldData
        req.newData = task
        req.operate = 1

        next()

        // await task.save()
        // response(res, 200, '成功', task)
    } catch (err) {
        next(err)
    }
}

// 删除任务
exports.deleteTask = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const model = await Task.findByIdAndDelete(taskId)
        //删除审核表里所属的顶级任务
        await Taskaudit.deleteMany({
            taskId
        })

        //删除该任务下的子任务
        await deletaTask(taskId)

        req.oldData = model
        // req.newData = {}
        req.operate = 3
        next()
        // response(res, 200, '删除成功')
    } catch (err) {
        next(err)
    }
}

// 删除单个文件
exports.deleteFile = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        var task = await TaskSubClass.findById(taskId)
        if (!task) {
            return response(res, 404, '找不到该任务', task)
        }
        var filename = req.query.filename
        fs.unlink(filename, (err) => {})
        if (!filename) {
            response(res, 404, '找不到该文件')
        }
        for (var i in task.fileAddress) {
            var tasksplit = task.fileAddress[i].split('/')
            var taskfile = tasksplit.pop()
            if (filename == taskfile) {
                task.fileAddress.splice(i, 1)
            }
        }
        const taskflie = new TaskSubClass(task)
        await taskflie.save()
        response(res, 200, '删除成功', task)
    } catch (err) {
        next(err)
    }
}

// 删除多个文件
exports.deleteAllFile = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        var task = await TaskSubClass.findById(taskId)
        if (!task) {
            return response(res, 404, '找不到该任务', task)
        }
        for (var i in task.fileAddress) {
            fs.unlink(task.fileAddress[i], (err) => {})
        }
        task.fileAddress = []
        const taskflie = new TaskSubClass(task)
        await taskflie.save()
        response(res, 200, '删除成功', task)
    } catch (err) {
        next(err)
    }
}

// 下载
exports.download = async (req, res, next) => {
    try {
        const taskId = req.params.taskId
        const task = await Task.find({
            _id: taskId
        })
        fileAddress = task[0].fileAddress
        response(res, 200, '下载', fileAddress)
    } catch (err) {
        next(err)
    }
}

// 职位
exports.position = async (req, res, next) => {
    try {
        const position = await Category.findOne({
            "name": "普通老师"
        })
        const positions = await User.find({
            "position": position._id
        })

        response(res, 200, '成功', positions)

    } catch (err) {
        next(err)
    }
}